<extend name="Public/layout" />

<block name="body">
    <style> ul, li { list-style: none; padding: 0; margin: 0; } #selectbox li { padding: 0 10px; line-height: 30px; cursor: pointer; } #selectbox li:hover { background: #eee; } #selectbox li.active { color: red; background: #eee; } .mt10 { margin-top: 10px; } .mb0 { margin-bottom: 0!important; } textarea.form-control { white-space: nowrap; overflow-y: auto; height: 200px; } .tip span { display: block; margin-right: 10px; } </style>
    <form method="post" id="jform" action="{:U('')}">
        <input type="hidden" name="key" value="{$cfgKey}"/>
        <div class="row">
            <div class="col-md-12">
                <div class="box box-info flat collapsed-box">
                    <div class="box-header with-border">
                        <h3 class="box-title">配置</h3>
                        <div class="box-tools pull-right">
                            <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-plus"></i>
                        </button>
                        </div>
                    </div>
                    <div class="box-body">
                        <div class="row">
                            <div class="col-md-12"><textarea style="height:700px;" class="form-control" name="cfg">{$cfg}</textarea></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-12">
                <div class="box box-success flat">
                    <div class="box-header with-border">
                        <h3 class="box-title">列表按钮</h3>
                        <div class="box-tools pull-right">
                            <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-plus"></i>
                        </button>
                        </div>
                    </div>
                    <div class="box-body">
                        <div class="row">
                            <div class="col-md-12 tip" style="margin-bottom:10px;">
                                <div class="row">
                                    <span class="col-md-12">type : hidden, num, string, textarea, date, datetime, select, radio, checkbox, editor, picture, file, callback, view</span>
                                    <span class="col-md-12">is_show : 1 始终显示, 2 新增显示, 3 编辑显示, 留空始终显示</span>
                                    <span class="col-md-12">extra : 枚举类型定义(0:禁用 ; 1:启用)</span>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12">
                                <textarea id="bt1" class="form-control" style="height:55px;"></textarea>
                            </div>
                        </div>
                        <div class="row mt10">
                            <div id="bc1" class="col-md-12"></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-12">
                <div class="box box-warning flat">
                    <div class="box-header with-border">
                        <h3 class="box-title">列表</h3>
                        <div class="box-tools pull-right">
                            <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-plus"></i>
                        </button>
                        </div>
                    </div>
                    <div class="box-body">
                        <div class="row">
                            <div class="col-md-12 tip" style="margin-bottom:10px;">
                                <div class="row">
                                    <span class="col-md-5">宽度 : id(30), 时间(100), 操作(35x +15),表头文字(15x)</span>
                                    <span class="col-md-5">排序 : 0 禁止, 默认可排序</span>
                                    <span class="col-md-5">搜索 : 0 禁止, 默认可搜索</span>
                                    <span class="col-md-5">筛选 : timerange(日期区间)</span>
                                    <span class="col-md-5">不可隐藏 : 1 强制显示, 默认可控制</span>
                                    <span class="col-md-5">排序方向 : desc / asc 默认按有此值的字段排序</span>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12" style="margin-bottom:10px;">
                                <input id="jj" class="form-control" />
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12">
                                <textarea id="jt" class="form-control"></textarea>
                            </div>
                        </div>
                        <div class="row mt10">
                            <div id="jd" class="col-md-12"></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-12">
                <div class="box box-success flat">
                    <div class="box-header with-border">
                        <h3 class="box-title">表单按钮</h3>
                        <div class="box-tools pull-right">
                            <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-plus"></i>
                        </button>
                        </div>
                    </div>
                    <div class="box-body">
                        <div class="row">
                            <div class="col-md-12 tip" style="margin-bottom:10px;">
                                <div class="row">
                                    <span class="col-md-12">type : hidden, num, string, textarea, date, datetime, select, radio, checkbox, editor, picture, file, callback, view</span>
                                    <span class="col-md-12">is_show : 1 始终显示, 2 新增显示, 3 编辑显示, 留空始终显示</span>
                                    <span class="col-md-12">extra : 枚举类型定义(0:禁用 ; 1:启用)</span>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12">
                                <textarea id="bt2" class="form-control" style="height:55px;"></textarea>
                            </div>
                        </div>
                        <div class="row mt10">
                            <div id="bc2" class="col-md-12"></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-12">
                <div class="box box-success flat">
                    <div class="box-header with-border">
                        <h3 class="box-title">表单</h3>
                        <div class="box-tools pull-right">
                            <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-plus"></i>
                        </button>
                        </div>
                    </div>
                    <div class="box-body">
                        <div class="row">
                            <div class="col-md-12 tip" style="margin-bottom:10px;">
                                <div class="row">
                                    <span class="col-md-12">type : hidden, num, string, textarea, date, datetime, select, radio, checkbox, editor, picture, file, callback, view</span>
                                    <span class="col-md-12">is_show : 1 始终显示, 2 新增显示, 3 编辑显示, 留空始终显示</span>
                                    <span class="col-md-12">extra : 枚举类型定义(0:禁用 ; 1:启用)</span>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12" style="margin-bottom:10px;">
                                <input id="fgt" class="form-control" />
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12">
                                <textarea id="fjt" class="form-control"></textarea>
                            </div>
                        </div>
                        <div class="row mt10">
                            <div id="fjd" class="col-md-12"></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-12">
                <div class="text-center">
                    <button type="submit" class="btn btn-primary btn-flat" style="width: 80px;margin-bottom:20px;">保存</button>
                </div>
            </div>
        </div>
    </form>
    <div id="j_e_c" style="display:none;"></div>

    <script>
        var resetSelectBoxEnable = {:$cfgKey?'"#j_e_c"':'false'};
    </script>

    <script>
        var modeliListEditor = (function() {

            var editor = function(configString, callback, container, configTemplate, sp) {
                this.config = [];
                this.callback = callback;
                this.container = container;
                this.editor = null;
                this.configTemplate = configTemplate;
                this.sp = sp || ':';
                this.setConfig(configString);
            };

            editor.prototype = {

                'setConfig': function(configString) {
                    this._parseConfig(configString);
                    this._createEditor();
                },

                '_parseConfig': function(configString) {
                    configString = typeof configString == 'string' ? configString : '';
                    this.config = configString.split('\n');
                    for (var i = 0; i < this.config.length; i++) {
                        this.config[i] = this.config[i].split(this.sp);
                    }
                },

                '_serializeConfig': function() {
                    var configStringArr = [];
                    var configStringArrTmp = [];
                    var context = this;
                    this.editor.find('tr').each(function(i) {
                        configStringArrTmp = [];
                        $(this).find('input').each(function() {
                            configStringArrTmp.push($.trim($(this).val()));
                        });
                        configStringArr.push(configStringArrTmp.join(context.sp));
                    });
                    return $.trim(configStringArr.join('\n'));
                },

                '_createEditor': function() {
                    var context = this;
                    var html = '';

                    this.editor = $('<table class="model_field_editor table table table-bordered table-condensed  mb0" />');
                    this.container.html('').append(this.editor);

                    html = '<tr>';
                    for (var i = 0; i < this.configTemplate.length; i++) {
                        html += '<td>' + this.configTemplate[i] + '</td>';
                    }
                    html += '</tr>';
                    for (var i = 0; i < this.config.length; i++) {
                        html += '<tr>';
                        for (var j = 0; j < this.configTemplate.length; j++) {
                            // 清理从php代码复制过来的引号和逗号
                            this.config[i][j] = this.config[i][j] ? this.config[i][j].replace(/^\s*['"]/, '') : '';
                            this.config[i][j] = this.config[i][j] ? this.config[i][j].replace(/['"](,)*\s*$/, '') : '';
                            html += '<td><input name="j" style="width:100%" value="' + (this.config[i][j] ? this.config[i][j] : '') + '"></td>';
                        }
                        html += '</tr>'
                    }
                    this.editor.append(html);

                    this.editor.delegate('input', 'change', function() {
                        context.callback(context._serializeConfig())
                    });
                }
            };

            return function(configString, callback, container, configTemplate, sp) {
                return new editor(configString, callback, container, configTemplate, sp);
            }
        })();

        var cfgel = $('textarea[name="cfg"]');
        var cfg = {};
        var textarea = $('#jt');
        var jinput = $('#jj');
        var container = $('#jd');
        var _name_ = null;
        var ftextarea = $('#fjt');
        var fcontainer = $('#fjd');
        var finput = $('#fgt');
        var fsp = ';;';
        var ftp = [
            'group',
            'name',
            'title',
            'type',
            'is_show',
            'extra',
            'remark'
        ];
        var btp = [
            'title',
            'url',
            'class',
            'icon',
            'callback',
            'param'
        ];
        var btextarea1 = $('#bt1');
        var btextarea2 = $('#bt2');
        var bcontainer1 = $('#bc1');
        var bcontainer2 = $('#bc2');

        // *********************************** 列按钮配置  ***********************************
        var beditor1 = modeliListEditor('', function(config) {
            btextarea1.val(config);
            setCfg();
        }, bcontainer1, btp, fsp);

        btextarea1.change(function() {
            beditor1.setConfig(btextarea1.val());
            setCfg();
        });

        // *********************************** 表单钮配置  ***********************************
        var beditor2 = modeliListEditor('', function(config) {
            btextarea2.val(config);
            setCfg();
        }, bcontainer2, btp, fsp);

        btextarea2.change(function() {
            beditor2.setConfig(btextarea2.val());
            setCfg();
        });

        // *********************************** 列配置  ***********************************
        var editor = modeliListEditor('', function(config) {
            textarea.val(config);
            setCfg();
        }, container, [
            '字段',
            '标题',
            '链接',
            '排序',
            '筛选',
            '宽度',
            '枚举',
            '搜索',
            '不可隐藏',
            '排序方向'
        ]);

        // 配置文本框数据改变时同步变更编辑器内容
        textarea.change(function() {
            editor.setConfig(textarea.val());
            setCfg();
        });

        // *********************************** 连表配置  ***********************************
        jinput.change(setCfg);

        // *********************************** 表单配置  ***********************************
        var feditor = modeliListEditor('', function(config) {
            ftextarea.val(config);
            setCfg();
        }, fcontainer, ftp, fsp);

        ftextarea.change(function() {
            feditor.setConfig(ftextarea.val());
            setCfg();
        });

        // *********************************** 分组配置  ***********************************
        finput.change(setCfg);

        // *********************************** 选择模型  ***********************************
        cfgel.change(function() {
            resetSelectBox();
        });

        // *********************************** 保存  ***********************************
        $('#jform').submit(function() {
            setCfg();
            $.post($(this).attr('action'),$(this).serialize(),function(){
                popup.tip('保存成功');
            });
            return false;
        });


        // 将变更的列配置写入配置输入框
        var setCfg = function() {
            var _cfg = getCfg();
            if (!_name_) {
                return false;
            }
            cfg[_name_] = _cfg;
            var val = "{";
            var t = [];
            var s = [];
            for (var x in cfg) {
                s.push(x);
            }
            s.sort();
            for (var i = 0; i < s.length; i++) {
                x = s[i];
                t.push('"' + x + '":' + JSON.stringify(cfg[x]));
            }
            val += "\n";
            val += t.join(",\n");
            val += "\n}";
            cfgel.val(val);
        };

        var getCfg = function() {
            var cfg = {};
            var _o = {};
            var _f = [];

            // 表单配置
            var _fa = ftextarea.val().split('\n');
            var fields = {};
            if($.trim(_fa)!=''){
                for (var i = 0; i < _fa.length; i++) {
                    _f = _fa[i].split(fsp);
                    _o = {};
                    for (var j = 0; j < _f.length; j++) {
                        _o[ftp[j]] = _f[j];
                    }
                    fields[_o.group] = fields[_o.group] || [];
                    fields[_o.group].push(_o);
                }
            }

            // 列表按钮配置
            var btns1 = [];
            var _v = btextarea1.val().split('\n');
            if($.trim(_v)!=''){
                for (var i = 0; i < _v.length; i++) {
                    _f = _v[i].split(fsp);
                    _o = {};
                    for (var j = 0; j < _f.length; j++) {
                        _o[btp[j]] = _f[j];
                    }
                    btns1.push(_o);
                }
            }

            // 表单按钮配置
            var btns2 = [];
            var _v = btextarea2.val().split('\n');
            if($.trim(_v)!=''){
                for (var i = 0; i < _v.length; i++) {
                    _f = _v[i].split(fsp);
                    _o = {};
                    for (var j = 0; j < _f.length; j++) {
                        _o[btp[j]] = _f[j];
                    }
                    btns2.push(_o);
                }
            }

            cfg.list_btns = btns1;
            cfg.list_grid = textarea.val();
            cfg.fields = fields;
            cfg.field_group = finput.val();
            cfg.list_join = jinput.val();
            cfg.form_btns = btns2;
            return cfg;
        };

        // 重置列选择器
        var resetSelectBox = function() {


            var box = $(resetSelectBoxEnable||'.sidebar-menu');
            cfg = JSON.parse(cfgel.val());
            var html = '';
            for (var x in cfg) {
                html += "<li><a href='javascript:;'>" + x + "</a></li>";
            }
            box.html(html);
            box.find('li').click(function() {
                _name_ = $.trim($(this).text());
                $(this).addClass('active').siblings().removeClass('active');

                // 重置列表按钮编辑器
                var fields = cfg[_name_].list_btns || [];
                var val = '';
                var a = [];
                var r = [];
                for (var i = 0; i < fields.length; i++) {
                    fields[i] = fields[i] || {};
                    r = [];
                    for (var j = 0; j < btp.length; j++) {
                        r.push(fields[i][btp[j]] == undefined ? '' : fields[i][btp[j]]);
                    }
                    a.push(r.join(fsp));
                }
                val = a.join("\n");
                btextarea1.val(val);
                beditor1.setConfig(val);
                if(!val){
                    btextarea1.closest('.box').addClass('collapsed-box');
                }else{
                    btextarea1.closest('.box').removeClass('collapsed-box');
                }

                // 重置表单按钮编辑器
                var fields = cfg[_name_].form_btns || [];
                var val = '';
                var a = [];
                var r = [];
                for (var i = 0; i < fields.length; i++) {
                    fields[i] = fields[i] || {};
                    r = [];
                    for (var j = 0; j < btp.length; j++) {
                        r.push(fields[i][btp[j]] == undefined ? '' : fields[i][btp[j]]);
                    }
                    a.push(r.join(fsp));
                }
                val = a.join("\n");
                btextarea2.val(val);
                beditor2.setConfig(val);
                if(!val){
                    btextarea2.closest('.box').addClass('collapsed-box');
                }else{
                    btextarea2.closest('.box').removeClass('collapsed-box');
                }

                // 重置列表编辑器
                cfg[_name_] = cfg[_name_] || {};
                var listgrid = typeof(cfg[_name_]) == 'string' ? cfg[_name_] : cfg[_name_].list_grid;
                textarea.val(listgrid);
                editor.setConfig(listgrid);
                if(!listgrid){
                    textarea.closest('.box').addClass('collapsed-box');
                }else{
                    textarea.closest('.box').removeClass('collapsed-box');
                }

                // 重制连表编辑器
                jinput.val(cfg[_name_].list_join);

                // 重置表单编辑器
                var fields = cfg[_name_].fields || {};
                var val = '';
                var a = [];
                var r = [];
                for (var x in fields) {
                    fields[x] = fields[x] || [];
                    for (var i = 0; i < fields[x].length; i++) {
                        fields[x][i] = fields[x][i] || [];
                        r = [];
                        for (var j = 0; j < ftp.length; j++) {
                            r.push(fields[x][i][ftp[j]] == undefined ? '' : fields[x][i][ftp[j]]);
                        }
                        a.push(r.join(fsp));
                    }
                }
                val = a.join("\n");
                ftextarea.val(val);
                feditor.setConfig(val);
                if(!val){
                    ftextarea.closest('.box').addClass('collapsed-box');
                }else{
                    ftextarea.closest('.box').removeClass('collapsed-box');
                }

                // 重置分组编辑器
                finput.val(cfg[_name_].field_group || "1:基础");

                localStorage.setItem('_list_editor_name_', _name_);
            });

            var index = 0;
            box.find('li').each(function(i) {
                if ($.trim($(this).text()) == localStorage.getItem('_list_editor_name_')) {
                    index = i;
                    return false;
                }
            });
            box.find('li').eq(index).click();
        };

        resetSelectBox();
        setCfg();
    </script>
</block>
